<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { loginModuleRecord } from '@/constants/app';
import { useAuthStore } from '@/store/modules/auth';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';

// eslint-disable-next-line vue/define-emits-declaration
const emit = defineEmits(['switch']);

defineOptions({
  name: 'PwdLogin'
});

// pinia状态管理，获得authStore实例
const authStore = useAuthStore();
const { formRef, validate } = useNaiveForm();

interface FormModel {
  userName: string;
  password: string;
  captcha: string;
}

const model: FormModel = reactive({
  userName: '',
  password: '',
  captcha: ''
});

const captchaText = ref('');

// 生成验证码
const generateCaptcha = () => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let result = '';
  for (let i = 0; i < 4; i += 1) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  captchaText.value = result;
};

// 刷新验证码
const refreshCaptcha = () => {
  generateCaptcha();
  model.captcha = '';
};

const rules = computed<Record<keyof FormModel, App.Global.FormRule[]>>(() => {
  const { formRules } = useFormRules();

  return {
    userName: formRules.userName,
    password: formRules.pwd,
    captcha: [
      { required: true, message: '请输入验证码', trigger: 'blur' },
      { min: 4, max: 4, message: '验证码为4位字符', trigger: 'blur' }
    ]
  };
});

async function handleSubmit() {
  await validate();

  // 验证验证码
  if (model.captcha.toUpperCase() !== captchaText.value) {
    window.$message?.error('验证码错误');
    refreshCaptcha();
    return;
  }

  await authStore.login(model.userName, model.password);
}

// 初始化验证码
onMounted(() => {
  generateCaptcha();
});
</script>

<template>
  <NForm ref="formRef" :model="model" :rules="rules" size="large" :show-label="false" @keyup.enter="handleSubmit">
    <NFormItem path="userName">
      <NInput v-model:value="model.userName" :placeholder="$t('page.login.common.userNamePlaceholder')" />
    </NFormItem>
    <NFormItem path="password">
      <NInput
        v-model:value="model.password"
        type="password"
        show-password-on="click"
        :placeholder="$t('page.login.common.passwordPlaceholder')"
      />
    </NFormItem>
    <NFormItem path="captcha">
      <div class="w-full flex space-x-2">
        <NInput v-model:value="model.captcha" placeholder="请输入验证码" class="flex-1" size="large" />
        <div
          class="h-10 w-20 flex cursor-pointer select-none items-center justify-center border border-indigo-300 rounded from-indigo-200 to-purple-200 bg-gradient-to-br text-base text-indigo-700 font-bold shadow transition-all duration-200 hover:from-indigo-300 hover:to-purple-300"
          title="点击刷新验证码"
          @click="refreshCaptcha"
        >
          {{ captchaText }}
        </div>
      </div>
    </NFormItem>
    <NSpace vertical :size="24">
      <div class="flex-y-center justify-between">
        <NCheckbox>{{ $t('page.login.pwdLogin.rememberMe') }}</NCheckbox>
        <NButton quaternary @click="emit('switch', 'reset-pwd')">
          {{ $t('page.login.pwdLogin.forgetPassword') }}
        </NButton>
      </div>
      <NButton type="primary" size="large" round block :loading="authStore.loginLoading" @click="handleSubmit">
        {{ $t('common.confirm') }}
      </NButton>
      <div class="flex-y-center justify-between gap-12px">
        <NButton class="flex-1" block @click="emit('switch', 'register')">
          {{ $t(loginModuleRecord.register) }}
        </NButton>
      </div>
    </NSpace>
  </NForm>
</template>

<style scoped></style>
